package com.tony.utils;

import net.sf.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: tony
 * @Date: 2018-11-30 17:36
 * @Description:
 */
public class BaiDuAIUtil {

    private static final String App_ID="14993955";
    private static final String App_KEY="Mpq5yHXPTewMNWaS6HZ0fd6n";
    private static final String Secret_Key="S37BClBOPp2iMu34I9afG3tGh2nOHHx1 ";


    private static final String Grant_Url="https://aip.baidubce.com/oauth/2.0/token?";
    private static final String General_Basic_Url="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?";

    public static void main(String[] args){
        String accessToken=getAccessToken();
        test(accessToken,"E:\\test\\test\\11.png");
    }


    public static String getAccessToken(){
        String url=Grant_Url+"grant_type=client_credentials&client_id="+App_KEY+"&client_secret="+Secret_Key;
        Map<String,String> headerMap=new HashMap<>();
        headerMap.put("Content-Type","application/x-www-form-urlencoded");
        String result=HttpUtil.getInstance(false,false).sendGet(url,headerMap);
        System.out.println(result);
        if(!TextUtil.isEmpty(result)){
            JSONObject data=JSONObject.fromObject(result);
            if(data!=null&&data.containsKey("access_token")){
                return data.getString("access_token");
            }
        }
        return "";
    }

    public static void test(String accessToken,String filePath){
        try {
            String url=General_Basic_Url+"access_token="+accessToken;

            Map<String,String> headerMap=new HashMap<>();
            headerMap.put("Content-Type","application/x-www-form-urlencoded");

            String imageBase64 = Base64.encodeToString(FileHelper.getBytesFromFile(new File(filePath)), 2);
            String encodedImage = URLEncoder.encode(imageBase64, "UTF-8");

            String params="image="+encodedImage;

            String result=HttpUtil.getInstance(false,false).sendPost(url,headerMap,params);
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

}
